<template>
  <div class="xmind-top-menu-bar">
    <div class="menu-modal">
      <el-popover ref="ElPovoverRef" placement="bottom-end" :show-arrow="false" :show-after="100" :teleported="false" popper-class="xmind-menu-list-popover">
        <div class="menu-list">
          <div
            class="menu-list-item"
            :class="{ 'x_border': item.border, 'x_disabled': item.disabled }"
            v-for="(item, index) in mindMenuList"
            :key="index">
            <div class="iitem" @click="handleOperateMenu(item.operate)">
              <i :class="item.icon" class="icon" :style="{ color: item.color }"></i>
              <p :style="{ color: item.color }">{{ item.name }}</p>
              <i v-if="item.children?.length" class="ri-arrow-right-s-line arrow_right"></i>
            </div>
            <ul
              class="ul-item-children"
              v-if="item.children?.length">
              <li
                class="flex"
                v-for="(itemName, idx) in item.children"
                :key="idx"
                @click="handleExportXmind(itemName.name)">
                <img :src="require(`@/assets/images/lengend/${itemName.name.toLowerCase()}.svg`)" alt="">
                <p>{{ itemName.name }}</p>
              </li>
            </ul>
          </div>
        </div>
        <template #reference>
          <div class="menu-icon">
            <img src="@/assets/images/menu.svg" alt="">
          </div>
        </template>
      </el-popover>
    </div>
    <el-icon class="is-loading" v-show="requestLoading">
      <Loading />
    </el-icon>
    <div class="xmind-name-editor" contenteditable="true" @blur="handlemindMapNameUpdate">{{ mindMapName }}</div>
    <NewFolderMind v-if="renameVisible" operateType="mind" :mindDetail="mindBasicInfo" @close-modal="handleCloseModal" />
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { initXmindMapJson } from '../config'
import { apiMindRename, apiCollectMind, apiUnCollectMind, apiCreateMind } from '@/apis/work'
import NewFolderMind from '@/pages/work/components/NewFolderMind.vue'

const emits = defineEmits(['export-xmind', 'import-file', 'new-map', 'search-map'])
const router = useRouter()
const props = defineProps({
  canvasList: {
    type: Array,
    default: () => []
  },
  mindBasicInfo: {
    type: Object,
    default: () => null
  }
})

const ElPovoverRef = ref()
const renameVisible = ref(false)
const mindMapName = ref('')
const isCollectMind = ref(0)
const mindMenuList = computed(() => {
  return [
    {
      name: '返回文件列表',
      icon: 'ri-arrow-left-line',
      operate: 'back-file',
      border: true
    },
    {
      name: '新建导图',
      icon: 'ri-ai-generate',
      operate: 'new-mind'
    },
    {
      name: '新建画布',
      icon: 'ri-stack-line',
      operate: 'new-map',
      disabled: props.canvasList.length >= 5
    },
    {
      name: '搜索',
      icon: 'ri-search-line',
      border: true,
      operate: 'search'
    },
    {
      name: '重命名',
      icon: 'ri-edit-line',
      operate: 'rename'
    },
    {
      name: isCollectMind.value ? '已收藏' : '添加至收藏',
      color: isCollectMind.value ? 'var(--el-color-primary)' : undefined,
      icon: isCollectMind.value ? 'ri-star-fill' : 'ri-star-line',
      border: true,
      operate: isCollectMind.value ? 'un-collect' : 'collect'
    },
    {
      name: '导入文件',
      icon: 'ri-upload-2-line',
      operate: 'import-file'
    },
    {
      name: '导出...',
      icon: 'ri-download-2-line',
      children: [
        { name: 'JPEG' },
        { name: 'PNG' },
        { name: 'SVG' },
        { name: 'PDF' },
        { name: 'JSON' },
        { name: 'XMIND' }
      ]
    },
    {
      name: '下载',
      icon: 'ri-download-cloud-line',
      operate: 'download',
      border: true
    },
    {
      name: '快捷键',
      icon: 'ri-keyboard-box-line',
      operate: 'shortkey'
    }
  ]
})

const requestLoading = ref(false)
/**
 * 导图重命名
 * @param {*} name
 */
async function handleMindRename (name) {
  requestLoading.value = true
  try {
    await apiMindRename({ name, id: props.mindBasicInfo.id })
  } finally {
    requestLoading.value = false
  }
}

function handleExportXmind (type) {
  emits('export-xmind', type.toLocaleUpperCase())
  ElPovoverRef.value.hide()
}

function handlemindMapNameUpdate (event) {
  const xmindName = event.target.innerText.replace(/^\s+/, '')
  if (!xmindName) {
    event.target.innerText = '未命名'
    mindMapName.value = event.target.innerText
    handleMindRename(mindMapName.value)
  } else if (event.target.innerText !== mindMapName.value) {
    if (event.target.innerText.length > 24) {
      event.target.innerText = mindMapName.value
      return ElMessage.info('导图名称不能超过24个字符')
    }
    mindMapName.value = event.target.innerText
    handleMindRename(mindMapName.value)
  }
}

async function handleOperateMenu (operateType) {
  switch (operateType) {
    case 'download':
      emits('export-xmind', 'GMIND')
      break
    case 'import-file':
      emits('import-file')
      break
    case 'new-map':
      emits('new-map')
      break
    case 'search':
      emits('search-map')
      break
    case 'new-mind':
      handleCreateMind()
      break
    case 'rename':
      renameVisible.value = true
      break
    case 'collect':
      handleChangeCollectStatus('collect')
      break
    case 'un-collect':
      handleChangeCollectStatus('un-collect')
      break
    case 'shortkey':
      emits('display-shortkey')
      break
    case 'back-file':
      if (window.history.length > 2) {
        router.go(-1)
      } else {
        router.replace('/home')
      }
      break
  }
  ElPovoverRef.value.hide()
}

/**
 * 新开浏览器创建导图
 */
const handleCreateMind = async () => {
  const mindJson = [initXmindMapJson()]
  const mindId = await apiCreateMind({
    name: '我的导图',
    mindJson
  })
  window.open(`/mind-map/${mindId}`)
}

/**
 * 导图收藏状态切换
 * @param {*} type
 */
async function handleChangeCollectStatus (type) {
  const API = type === 'collect' ? apiCollectMind : apiUnCollectMind
  await API(props.mindBasicInfo.id)
  ElMessage.success('操作成功')
  isCollectMind.value = Number(type === 'collect')
}

function handleCloseModal (refresh, detail) {
  renameVisible.value = false
  if (refresh) {
    mindMapName.value = detail.name
  }
}

watch(() => props.mindBasicInfo, newVal => {
  mindMapName.value = newVal?.name
}, { deep: true })

watch(() => props.mindBasicInfo, newVal => {
  isCollectMind.value = newVal?.isCollected
}, { deep: true })
</script>

<style scoped lang="scss">
.xmind-top-menu-bar {
  position: fixed;
  left: 20px;
  top: 20px;
  background-color: #fff;
  padding: 8px 6px;
  border-radius: 6px;
  box-shadow: inset 0px 0px 3px 0px rgba(255, 255, 255, 0.1), 0px 0px 3px 0px rgba(0, 0, 0, 0.14), 0px 8px 40px 0px rgba(0, 0, 0, 0.06);
  display: flex;
  align-items: center;
  cursor: url('~@/assets/images/default.png' ) 4 4, auto;
  z-index: 5;
  .menu-modal {
    margin: 0 4px 0 0;
    position: relative;
    &:after {
      content: "";
      position: absolute;
      width: 1px;
      top: 6px;
      bottom: 6px;
      background-color: #f1f1f1;
      right: -6px;
    }
    .menu-icon {
      padding: 2px 6px;
      border-radius: 4px;
      font-size: 0;
      &:hover {
        background-color: rgba(0, 0, 0, 0.05);
      }
    }
  }
  .xmind-name-editor {
    padding: 0 6px;
    margin: 0 8px;
    outline: none;
    width: 210px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #000;
    font-size: 13px;
    position: relative;
    top: -1px;
  }
  .is-loading {
    color: #999;
  }
}
</style>
